//
//  ServerDetailSelectServerTypeCell.m
//  ServerDetailDemo
//
//  Created by apple on 15/12/16.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "ServerDetailSelectServerTypeCell.h"
#define kleftSpace 15
#define ktopSpace 15
#define kVSpace 14
#define kHSpace 10
#define kitemHight 33
#define kcolumnNumber 2
#define VIEW_WIDTH [UIScreen mainScreen].bounds.size.width//屏幕宽度
#define VIEW_HEIGHT [UIScreen mainScreen].bounds.size.height//屏幕高度
//untils
#import "NSString+TextSize.h"
#import "UIColor+Hex.h"
#import "Global.h"
@interface ServerDetailSelectServerTypeCell () {
    NSInteger _currentSelectedIndex;
    NSInteger _oldSelectedIndex;
}
@property(nonatomic, strong)NSMutableArray *items;//存放button
@property(nonatomic, strong)NSMutableArray *dataSource;//存放数据源
@end
@implementation ServerDetailSelectServerTypeCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _currentSelectedIndex = 0;
        _oldSelectedIndex = 0;
        _items = [[NSMutableArray alloc]init];
        _dataSource = [[NSMutableArray alloc]init];
        [self updateDataWithDataArr:[NSArray array]];
    }
    return self;
}
- (void)updateDataWithDataArr:(NSArray*)dataArr {
    [_dataSource removeAllObjects];
    if ([dataArr count] != 0) {
        [_dataSource addObjectsFromArray:dataArr];
        NSString *cellTitle = @"请选择：";
        CGSize cellTitleSize = [cellTitle sizeWithFont:[UIFont systemFontOfSize:FontSize(15)] maxSize:CGSizeMake(80, kitemHight)];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(kleftSpace
                                                                      ,ktopSpace
                                                                      , cellTitleSize.width
                                                                       , kitemHight)];
        titleLabel.font = [UIFont systemFontOfSize:FontSize(15)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor colorWithHexString:@"#555555"];
        titleLabel.text = cellTitle;
        [self.contentView addSubview:titleLabel];
        //初始化item
        CGFloat currentWidth = CGRectGetMaxX(titleLabel.frame);
        CGFloat currentHeight = CGRectGetMinY(titleLabel.frame);
        CGSize currentSize = CGSizeZero;
        CGFloat maxWidth = VIEW_WIDTH-15;
        UIFont *titleFont = [UIFont systemFontOfSize:FontSize(15)];
        UIImage *normalImage = [UIImage imageNamed:@"Servicedetails_bg_selectbox_normal"];
        UIImage *selectedImage = [UIImage imageNamed:@"Servicedetails_bg_selectbox_checked"];
        UIEdgeInsets insets = UIEdgeInsetsMake(8, 3, 8, 3);
        normalImage = [normalImage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        selectedImage = [selectedImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
            for (NSInteger index=0; index<dataArr.count; index++) {
                NSString *buttonTitle =[NSString stringWithFormat:@" %@ ",[[dataArr objectAtIndex:index] objectForKey:@"TITLE"]];
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setTag:index];
                [button setTitle:buttonTitle forState:UIControlStateNormal];
                [button.titleLabel setFont:titleFont];
                [button setBackgroundImage:normalImage forState:UIControlStateNormal];
                [button setBackgroundImage:selectedImage forState:UIControlStateSelected];
                [button setBackgroundImage:selectedImage forState:UIControlStateHighlighted];
                button.backgroundColor = [UIColor clearColor];
                button.titleLabel.font = [UIFont systemFontOfSize:FontSize(15)];
                [button setTitleColor:[UIColor colorWithHexString:@"#555555"] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateSelected];
                [button setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateHighlighted];
                [button addTarget:self action:@selector(selectedServerTypeEvent:) forControlEvents:UIControlEventTouchUpInside];
                

                //实际字体size
                currentSize = [self computeSizeFromString:buttonTitle];
                if (currentSize.width >= maxWidth) {//大于屏幕预留宽度
                    
                    CGFloat height = ((int)currentSize.width % (int)maxWidth ? currentSize.width / maxWidth : currentSize.width / maxWidth + 1) * currentSize.height;
                    button.frame = CGRectMake(currentWidth, currentHeight, maxWidth, height);
                    currentHeight = currentHeight + height + 10.0f;
                    currentWidth = CGRectGetMaxX(titleLabel.frame);
                }else {
                    
                    if(currentSize.width + currentWidth < maxWidth) {//宽度小于一行
                        
                        button.frame = CGRectMake(currentWidth, currentHeight, currentSize.width, currentSize.height);
                        currentWidth = currentWidth + currentSize.width + 5.0f;
                    }else if (currentSize.width + currentWidth == maxWidth) {//刚好一行
                        
                        button.frame = CGRectMake(currentWidth, currentHeight, currentSize.width, currentSize.height);
                        currentWidth = CGRectGetMaxX(titleLabel.frame);
                        currentHeight = currentHeight + currentSize.height + 10.0f;
                    }else if(currentSize.width + currentWidth > maxWidth ) {//换行
                        
                        currentWidth = CGRectGetMaxX(titleLabel.frame);
                        currentHeight = currentHeight + currentSize.height + 10.0f;
                        button.frame = CGRectMake(currentWidth, currentHeight, currentSize.width, currentSize.height);
                        currentWidth = currentWidth + currentSize.width + 5.0f;
                    }
                }
                [self.contentView addSubview:button];
                [self.items addObject:button];
                if (index== 0) {//默认第一个选中
                    button.selected = YES;
                }
             }

//        //        item宽度
//        CGFloat itemWidth = (VIEW_WIDTH - 2*kleftSpace - 2*kHSpace - CGRectGetWidth(titleLabel.bounds))/2;
//        //行数
//        NSInteger lineNum = 0;
//        if (dataArr.count % kcolumnNumber != 0) {//最后一行为一个
//            lineNum = dataArr.count/kcolumnNumber + 1;
//        } else {
//            lineNum = dataArr.count/kcolumnNumber;
//        }
//        //item Y坐标
//        CGFloat y = 0;
//        //item 下标
//        NSInteger index = 0;
//        UIImage *normalImage = [UIImage imageNamed:@"Servicedetails_bg_selectbox_normal"];
//        UIImage *selectedImage = [UIImage imageNamed:@"Servicedetails_bg_selectbox_checked"];
//        UIEdgeInsets insets = UIEdgeInsetsMake(8, 3, 8, 3);
//        normalImage = [normalImage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
//        selectedImage = [selectedImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
//        for (NSInteger i = 0; i < lineNum; i++) {//行
//            y = CGRectGetMinY(titleLabel.frame) + (kitemHight + kVSpace)*i;
//            for (NSInteger j = 0; j < kcolumnNumber; j++) {//列
//                if (i == lineNum - 1) {//最后一行进行特殊判断
//                    if (dataArr.count % kcolumnNumber != 0 && j == kcolumnNumber -1) {//最后一行为一个
//                        return ;
//                    }
//                }
//                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//                button.frame = CGRectMake(CGRectGetMaxX(titleLabel.frame) + kHSpace + (itemWidth + kHSpace)*j
//                                          , y
//                                          , itemWidth
//                                          , kitemHight);
//                
//                [button setTitle:[[dataArr objectAtIndex:index] objectForKey:@"TITLE"] forState:UIControlStateNormal];
//                [button setBackgroundImage:normalImage forState:UIControlStateNormal];
//                [button setBackgroundImage:selectedImage forState:UIControlStateSelected];
//                [button setBackgroundImage:selectedImage forState:UIControlStateHighlighted];
//                button.backgroundColor = [UIColor clearColor];
//                button.titleLabel.font = [UIFont systemFontOfSize:12];
//                [button setTitleColor:[UIColor colorWithHexString:@"#555555"] forState:UIControlStateNormal];
//                [button setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateSelected];
//                [button setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateHighlighted];
//                button.titleLabel.minimumScaleFactor = 0.8;
//                button.titleLabel.adjustsFontSizeToFitWidth = YES;
//                button.tag = index;
//                [button addTarget:self action:@selector(selectedServerTypeEvent:) forControlEvents:UIControlEventTouchUpInside];
//                [self.contentView addSubview:button];
//                [self.items addObject:button];
//                if (i == 0 && j == 0) {//默认第一个选中
//                    button.selected = YES;
//                }
//                index ++;
//            }
//        }


        
    }
       
}
    

//计算字符的长度和宽度
-(CGSize)computeSizeFromString:(NSString *)string {
    CGSize maxSize = CGSizeMake(VIEW_WIDTH, 30);
    CGSize curSize = [string boundingRectWithSize:maxSize
                                          options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                       attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:FontSize(16)] }
                                          context:nil].size;
    return CGSizeMake(ceilf(curSize.width), 30);
    
}
- (void)selectedServerTypeEvent:(id)sender {
    UIButton *button = (UIButton*)sender;
    _oldSelectedIndex = _currentSelectedIndex;
    _currentSelectedIndex = button.tag;
    [self changeButtonStyle];
    if (_delegate && [_delegate respondsToSelector:@selector(selectedItemWithTag:itemData:)]) {
        [_delegate selectedItemWithTag:_currentSelectedIndex itemData:[self.dataSource objectAtIndex:_currentSelectedIndex]];
    }
}

- (void)changeButtonStyle {
    UIButton *oldBtn = (UIButton*)[self.items objectAtIndex:_oldSelectedIndex];
    UIButton *currentBtn = (UIButton*)[self.items objectAtIndex:_currentSelectedIndex];
    oldBtn.selected = NO;
    currentBtn.selected = YES;
}
//计算实际高度
- (CGFloat)cellFactHight {
    
    if (self.items.count != 0) {
        UIButton *firstBtn = (UIButton*)[self.items firstObject];
        UIButton *lastBtn = (UIButton*)[self.items lastObject];
        return CGRectGetMaxY(lastBtn.frame) - CGRectGetMinY(firstBtn.frame) + 2*ktopSpace;
    }
    return 44;
}
- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
